package com.dy.lock.screen.component.impl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.UserInfoComponent;
import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.GtPushCodeDes;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.jersey.api.EasemobIMUsers;
import com.dy.lock.screen.pojo.AdvertOperatorInfo;
import com.dy.lock.screen.pojo.CustomerAttentionInfo;
import com.dy.lock.screen.pojo.CustomerClientInfo;
import com.dy.lock.screen.pojo.CustomerMarkInfo;
import com.dy.lock.screen.pojo.ScoreInfo;
import com.dy.lock.screen.pojo.SmsAuthCodeInfo;
import com.dy.lock.screen.pojo.UserInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.AdvertOperatorService;
import com.dy.lock.screen.service.CustomerAttentionService;
import com.dy.lock.screen.service.CustomerClientService;
import com.dy.lock.screen.service.CustomerMarkRelationService;
import com.dy.lock.screen.service.ScoreService;
import com.dy.lock.screen.service.SmsAuthCodeService;
import com.dy.lock.screen.service.UserService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.utils.DateUtil;
import com.dy.lock.screen.utils.GtPushUtil;
import com.dy.lock.screen.vo.GtPushMessageVo;
import com.dy.lock.screen.vo.UserVo;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.Gson;

@Component("userInfoComponent")
public class UserInfoComponentImpl implements UserInfoComponent {

	private static final Logger log = Logger
			.getLogger(UserInfoComponentImpl.class);
	private Gson gson;
	@Resource(name = "smsService")
	private SmsAuthCodeService authCodeService;
	@Resource(name = "userService")
	private UserService userService;
	@Resource(name = "scoreService")
	private ScoreService scoreService;
	@Resource(name = "customerClientService")
	private CustomerClientService customerClientService;
	@Resource(name = "advertOperatorService")
	private AdvertOperatorService advertOperatorService;
	@Resource(name = "customerAttentionService")
	private CustomerAttentionService customerAttentionService;
	@Resource(name = "customerMarkRelationService")
	private CustomerMarkRelationService customerMarkRelationService;

	public UserInfoComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public UserVo getAuthCode(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			String mobile = vo.getMobile();
			List<SmsAuthCodeInfo> smsCodes = this.authCodeService
					.queryByMobile(mobile, head);
			if (smsCodes != null && smsCodes.size() > 3) {
				log
						.info("requestId:" + head.getRequestId()
								+ ",验证码获取次数超过3次限制。");
				throw new ServerDisponseException(
						TransmissionCode.AUTH_CODE_OVER_LIMIT.getCode(),
						TransmissionCode.AUTH_CODE_OVER_LIMIT.getMessage());
			}
			UserInfo userInfo = this.userService.queryByMobile(vo.getMobile(),
					head);
			if ("1".equals(vo.getRegister())) {
				if (userInfo != null) {
					log.info("requestId:" + head.getRequestId() + ",此手机号码已注册。");
					throw new ServerDisponseException(
							TransmissionCode.MOBILE_IS_USED.getCode(),
							TransmissionCode.MOBILE_IS_USED.getMessage());
				}
			} else {
				if (userInfo == null) {
					log.info("requestId:" + head.getRequestId()
							+ ",忘记密码时，此手机号码还没有注册。");
					throw new ServerDisponseException(
							TransmissionCode.MOBILE_IS_NOT_USED.getCode(),
							TransmissionCode.MOBILE_IS_NOT_USED.getMessage());
				}
			}
			UserVo user = new UserVo();
			user.setMobile(mobile);
			user.setAuthCode(CommonUtil.createRandomNumber());
			for (int i = 0; i < 20; i++) {
				SmsAuthCodeInfo info = this.authCodeService
						.queryByMobileAndCode(mobile, user.getAuthCode(), head);
				if (info != null) {
					user.setAuthCode(CommonUtil.createRandomNumber());
				} else {
					break;
				}
			}
			int re = this.saveAuthCode(user, head);
			if (re > 0) {
				return user;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取验证码时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	private int saveAuthCode(UserVo user, Head head) {
		int re = -1;
		try {
			SmsAuthCodeInfo info = new SmsAuthCodeInfo();
			info.setId(UUID.randomUUID().toString());
			info.setMobile(user.getMobile());
			info.setCreateTime(new Date());
			info.setAuthCode(user.getAuthCode());
			re = this.authCodeService.save(info, head);
		} catch (Exception e) {
			log.error("requestId:" + head.getRequestId() + ",保存短信验证码信息异常", e);
		}
		return re;
	}

	@Override
	public UserVo checkAuthCode(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			SmsAuthCodeInfo info = this.authCodeService.queryByMobileAndCode(vo
					.getMobile(), vo.getAuthCode(), head);
			if (info != null) {
				Date createAuthTime = info.getCreateTime();
				Date currentTime = new Date();
				int ten = 10 * 60;
				long between = (currentTime.getTime() - createAuthTime
						.getTime()) / 1000;
				if (between > ten) {
					log.info("requestId:" + head.getRequestId() + ",手机验证码已过时。");
					throw new ServerDisponseException(
							TransmissionCode.AUTH_CODE_TIME_OUT.getCode(),
							TransmissionCode.AUTH_CODE_TIME_OUT.getMessage());
				} else {
					UserVo u = new UserVo();
					u.setMobile(info.getMobile());
					u.setAuthCode(info.getAuthCode());
					return u;
				}
			} else {
				log.info("requestId:" + head.getRequestId() + ",验证码查询异常。");
				throw new ServerDisponseException(
						TransmissionCode.AUTH_CODE_ERROR.getCode(),
						TransmissionCode.AUTH_CODE_ERROR.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",校验验证码时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public UserVo register(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			UserInfo userInfo = this.userService.queryByMobile(vo.getMobile(),
					head);
			if (userInfo != null) {
				log.info("requestId:" + head.getRequestId() + ",此手机号码已注册。");
				throw new ServerDisponseException(
						TransmissionCode.MOBILE_IS_USED.getCode(),
						TransmissionCode.MOBILE_IS_USED.getMessage());
			}
			vo.setUserId(CommonUtil.createRandomNo(8));
			for (int i = 0; i < 20; i++) {
				UserInfo info = this.userService.queryByPrimaryKey(vo
						.getUserId(), head);
				if (info != null) {
					vo.setUserId(CommonUtil.createRandomNo(8));
				} else {
					break;
				}
			}
			int re = this.saveUser(vo, head);
			if (re > 0) {
				if (StringUtils.isNotBlank(vo.getDeviceId())) {
					CustomerClientInfo cci = new CustomerClientInfo();
					cci.setDeviceId(vo.getDeviceId());
					cci.setCustomerId(vo.getUserId());
					cci.setInsertTime(new Date());
					if (StringUtils.isNotBlank(vo.getClientId())) {
						cci.setClientId(vo.getClientId());
					}
					int cuRe = this.customerClientService.save(cci, head);
					if (cuRe <= 0) {
						throw new ServerDisponseException(
								TransmissionCode.OPERATOR_EXCEPTION.getCode(),
								TransmissionCode.OPERATOR_EXCEPTION
										.getMessage());
					}
				}
				// 注册环信用户账号--- 注册IM用户[单个]
				ObjectNode result = EasemobIMUsers.registerIMUser(vo
						.getUserId(), vo.getUserId());
				if (result != null && 200 == result.get("statusCode").asInt()) {
					log.info("requestId:" + head.getRequestId()
							+ ",注册用户时,注册环信用户账号成功。");
				}
				if (StringUtils.isNotBlank(vo.getInviteCode())) {
					UserInfo u = this.userService.queryByMyInviteCode(vo
							.getInviteCode(), head);
					if (u != null) {
						String userId = u.getUserId();
						ScoreInfo sc = this.scoreService
								.queryByPrimaryKey(userId);
						ScoreInfo scIn = new ScoreInfo();
						scIn.setCustomerId(userId);
						scIn.setCustomerName(u.getUserName());
						int scRe = -1;
						if (sc == null) {
							scIn.setInvitationScore(Constant.INVITATION_SCORE);
							scIn.setExchangedScore(Constant.INVITATION_SCORE);
							scIn.setTotalScore(Constant.INVITATION_SCORE);
							scIn.setInsertTime(new Date());
							scRe = this.scoreService.save(scIn);
						} else {
							Integer totalInviteScore = CommonUtil.add(sc
									.getInvitationScore(),
									Constant.INVITATION_SCORE);
							Integer totalExchangeScore = CommonUtil.add(sc
									.getExchangedScore(),
									Constant.INVITATION_SCORE);
							Integer totalScore = CommonUtil
									.add(sc.getTotalScore(),
											Constant.INVITATION_SCORE);
							scIn.setInvitationScore(totalInviteScore);
							scIn.setExchangedScore(totalExchangeScore);
							scIn.setTotalScore(totalScore);
							scIn.setUpdateTime(new Date());
							scRe = this.scoreService.updateScore(scIn);
						}
						if (scRe > 0) {
							AdvertOperatorInfo adOpt = new AdvertOperatorInfo();
							adOpt.setUserId(userId);
							adOpt.setAdScore(Constant.INVITATION_SCORE);
							adOpt
									.setOperatorType(Constant.ADVERT_OPERATE_INVITE);
							this.advertOperatorService.save(adOpt, head);
						}
					}
				}
				return vo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",注册用户时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	private int saveUser(UserVo user, Head head) {
		int re = -1;
		try {
			UserInfo info = new UserInfo();
			info.setUserId(user.getUserId());
			info.setMobile(user.getMobile());
			info.setUserPwd(user.getPassword());
			info.setInvitationCode(user.getInviteCode());
			info.setRegisterTime(new Date());
			info.setStatus(Constant.USER_ON_LINE);
			if (StringUtils.isBlank(user.getUserSource())) {
				info.setUserSource(Constant.USER_SOURCE_ANDROID);
			} else {
				info.setUserSource(user.getUserSource());
			}
			info.setMyInvitationCode(CommonUtil.createRandomNo(6));
			for (int i = 0; i < 20; i++) {
				UserInfo u = this.userService.queryByMyInviteCode(info
						.getMyInvitationCode(), head);
				if (u != null) {
					info.setMyInvitationCode(CommonUtil.createRandomNo(6));
				} else {
					break;
				}
			}
			re = this.userService.save(info, head);
		} catch (Exception e) {
			log.error("requestId:" + head.getRequestId() + ",保存用户信息异常", e);
		}
		return re;
	}

	@Override
	public UserVo forgetPassword(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			UserInfo user = new UserInfo();
			user.setMobile(vo.getMobile());
			user.setUserPwd(vo.getPassword());
			UserInfo userInfo = this.userService.queryByMobile(vo.getMobile(),
					head);
			int re = this.userService.updatePwd(user, head);
			if (re > 0 && userInfo != null) {
				vo.setUserId(userInfo.getUserId());
				return vo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",忘记密码时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public UserVo login(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			UserInfo user = this.userService
					.queryByMobile(vo.getMobile(), head);
			if (user == null || !user.getUserPwd().equals(vo.getPassword())) {
				log.info("requestId:" + head.getRequestId() + ",用户名或密码错误!");
				throw new ServerDisponseException(
						TransmissionCode.USER_OR_PASSWORD_ERROR.getCode(),
						TransmissionCode.USER_OR_PASSWORD_ERROR.getMessage());
			}
			if (Constant.USER_LOCKED.equals(user.getStatus())) {
				log.info("requestId:" + head.getRequestId() + ",用户被锁定!");
				throw new ServerDisponseException(
						TransmissionCode.USER_IS_LOCKED.getCode(),
						TransmissionCode.USER_IS_LOCKED.getMessage());
			}
			UserInfo userInfo = new UserInfo();
			userInfo.setUserId(user.getUserId());
			userInfo.setStatus(Constant.USER_ON_LINE);
			userInfo.setLastLoginTime(new Date());
			int re = this.userService.update(userInfo, head);
			if (re > 0) {
				CustomerClientInfo cci = this.customerClientService
						.queryByPrimaryKey(user.getUserId());
				if (StringUtils.isNotBlank(vo.getDeviceId())) {
					if (cci != null) {
						// 更新clientId
						CustomerClientInfo ccInfo = new CustomerClientInfo();
						ccInfo.setDeviceId(vo.getDeviceId());
						ccInfo.setCustomerId(user.getUserId());
						ccInfo.setUpdateTime(new Date());
						int cu = this.customerClientService
								.update(ccInfo, head);
						if (cu <= 0) {
							log.info("requestId:" + head.getRequestId()
									+ ",用户登录时，更新设备ID异常。");
							throw new ServerDisponseException(
									TransmissionCode.OPERATOR_EXCEPTION
											.getCode(),
									TransmissionCode.OPERATOR_EXCEPTION
											.getMessage());
						}
					}
				}
				if (StringUtils.isNotBlank(vo.getClientId())) {
					if (cci != null) {
						String clientIdDB = cci.getClientId();
						String clientId = vo.getClientId();
						if (!clientId.equals(clientIdDB)) {
							// // // 推送消息到单个用户app
							GtPushMessageVo pushVo = new GtPushMessageVo();
							pushVo.setCode(Integer
									.parseInt(GtPushCodeDes.REPEAT_LOGIN
											.getCode()));
							pushVo.setUserId(user.getUserId());
							pushVo.setMessageContent(GtPushCodeDes.REPEAT_LOGIN
									.getDescription());
							pushVo.setMessageTime(new Date());
							pushVo.setMessageTitle("用户强制下线");
							String pushJson = CommonUtil.gson().toJson(pushVo);
							//				
							Map<String, Object> result = null;
							try {
								result = GtPushUtil.pushToSingle(clientIdDB,
										pushJson, null);
							} catch (Exception e) {
								log.error("requestId:" + head.getRequestId()
										+ ",登录时，推送消息异常", e);
							}
							if (result != null) {
								log.info("requestId:" + head.getRequestId()
										+ ",推送消息返回结果：" + result);
							}

							// 更新clientId
							CustomerClientInfo ccInfo = new CustomerClientInfo();
							ccInfo.setClientId(clientId);
							ccInfo.setCustomerId(user.getUserId());
							ccInfo.setUpdateTime(new Date());
							int cu = this.customerClientService.update(ccInfo,
									head);
							if (cu <= 0) {
								log.info("requestId:" + head.getRequestId()
										+ ",用户登录时，更新clientID异常。");
								throw new ServerDisponseException(
										TransmissionCode.OPERATOR_EXCEPTION
												.getCode(),
										TransmissionCode.OPERATOR_EXCEPTION
												.getMessage());
							}
						}
					}
				}
				vo.setMobile(user.getMobile());
				vo.setUserId(userInfo.getUserId());
				return vo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}

		} else {
			log.info("requestId:" + head.getRequestId() + ",用户登录时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public boolean updateAccount(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			String headerPath = "";
			String base64Str = vo.getPortrait();
			if (StringUtils.isNotBlank(base64Str)) {
				headerPath = Constant.USER_HEADER_PATH + vo.getUserId() + "_"
						+ DateUtil.format(new Date(), "yyyyMMddHHmmss")
						+ ".jpg";
				String imgFilePath = CommonUtil.getPhotoLocation() + headerPath;// 新生成的图片
				File file = new File(CommonUtil.getPhotoLocation()
						+ Constant.USER_HEADER_PATH);
				if (!file.exists()) {
					file.mkdirs();
				}
				CommonUtil.saveBase64Image(base64Str, imgFilePath);
			}

			UserInfo info = new UserInfo();
			info.setHeaderPath(headerPath);
			info.setUserId(vo.getUserId());
			info.setAgent(vo.getSex());
			info.setUserName(vo.getNickName());
			info.setPersonalSign(vo.getPersonalSign());
			if (!StringUtils.isEmpty(vo.getBirthday())) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					info.setBirthday(sdf.parse(vo.getBirthday()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			int re = this.userService.update(info, head);
			if (re > 0) {
				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",修改用户信息时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public UserVo getAccount(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			String userId = vo.getUserId();
			UserInfo userinfo = this.userService.queryByUserId(userId, head);
			if (userinfo != null) {
				vo.setUserId(userinfo.getUserId());
				vo.setInviteCode(userinfo.getMyInvitationCode());
				vo.setNickName(userinfo.getUserName());
				vo.setSex(userinfo.getAgent());
				vo.setBirthday(DateUtil.format(userinfo.getBirthday()));
				if (StringUtils.isNotBlank(userinfo.getHeaderPath())) {
					vo.setPortrait(CommonUtil
							.getUrlPrefixApi("photo.url.prefix.path.api")
							+ userinfo.getHeaderPath());
				}
				return vo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取验证码时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public UserVo updatePwd(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			UserInfo userinfo = this.userService.queryByUserId(vo.getUserId(),
					head);
			if (userinfo == null
					|| !vo.getOldPassword().equals(userinfo.getUserPwd())) {
				throw new ServerDisponseException(
						TransmissionCode.OLD_PASSWORD_ERROR.getCode(),
						TransmissionCode.OLD_PASSWORD_ERROR.getMessage());
			}
			UserInfo user = new UserInfo();
			user.setUserId(vo.getUserId());
			user.setUserPwd(vo.getPassword());
			int re = this.userService.update(user, head);
			if (re > 0) {
				return vo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",修改密码时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public boolean checkUser(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			CustomerClientInfo cci = this.customerClientService
					.queryByPrimaryKey(vo.getUserId());
			if (cci != null && vo.getDeviceId().equals(cci.getDeviceId())) {
				return true;
			} else {
				return false;
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",校验验用户时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public UserVo uploadCilentId(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			CustomerClientInfo cci = this.customerClientService
					.queryByPrimaryKey(vo.getUserId());
			CustomerClientInfo ccInfo = new CustomerClientInfo();
			ccInfo.setCustomerId(vo.getUserId());
			ccInfo.setClientId(vo.getClientId());
			int re = -1;
			if (cci != null) {
				ccInfo.setUpdateTime(new Date());
				re = this.customerClientService.update(ccInfo, head);
			} else {
				ccInfo.setInsertTime(new Date());
				re = this.customerClientService.save(ccInfo, head);
			}
			if (re > 0) {
				return vo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",上传设备唯一标示时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<UserVo> list(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			String markId = vo.getMarkId();
			String userId = vo.getUserId();
			List<String> userIds = new ArrayList<String>();
			CustomerAttentionInfo attentionId = new CustomerAttentionInfo();
			attentionId.setAttentionId(userId);
			userIds = customerAttentionService.queryByAidOrBeid(attentionId);
			if (userIds == null || userIds.isEmpty()) {
				userIds = new ArrayList<String>();
			}
			userIds.add(userId);
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("pageStart", pageStart);
			paraMap.put("pageEnd", pageEnd);
			paraMap.put("markId", markId);
			paraMap.put("userIds", userIds);
			List<UserVo> list = new ArrayList<UserVo>();
			List<UserInfo> userList = this.userService.queryPage(paraMap);
			if (userList != null && !userList.isEmpty()) {
				for (UserInfo usr : userList) {
					UserVo uvo = new UserVo();
					uvo.setUserId(usr.getUserId());
					uvo.setNickName(usr.getUserName());
					if (StringUtils.isNoneBlank(usr.getHeaderPath())) {
						uvo.setPortrait(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ usr.getHeaderPath());
					}
					uvo.setPersonalSign(usr.getPersonalSign());
					uvo.setCommentNum(usr.getCommentNum());
					uvo.setFansNum(usr.getFansNum());
					uvo.setBirthday(DateUtil.format(usr.getBirthday()));
					uvo.setSex(usr.getAgent());
					CustomerAttentionInfo att = new CustomerAttentionInfo();
					att.setAttentionId(userId);
					att.setBeConcernedId(usr.getUserId());
					CustomerAttentionInfo atten = this.customerAttentionService
							.queryByAidAndBeid(att);
					if (atten != null) {
						uvo.setAttentioned(true);
					}
					List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
							.queryListByCid(usr.getUserId());
					uvo.setMarkInfoList(markInfos);
					list.add(uvo);
				}
			}
			return list;

		} else {
			log.info("requestId:" + head.getRequestId() + ",获取标识用户列表时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public UserVo getPersonalInfo(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			UserInfo usr = this.userService.queryPersonalInfoByUserId(vo
					.getBeViewedId());
			if (usr != null) {
				UserVo uvo = new UserVo();
				uvo.setUserId(usr.getUserId());
				if (StringUtils.isNotBlank(usr.getUserName())) {
					uvo.setNickName(usr.getUserName());
				} else {
					uvo.setNickName(usr.getUserId());
				}
				if (StringUtils.isNoneBlank(usr.getHeaderPath())) {
					uvo.setPortrait(CommonUtil
							.getUrlPrefixApi("photo.url.prefix.path.api")
							+ usr.getHeaderPath());
				}
				uvo.setPersonalSign(usr.getPersonalSign());
				uvo.setCommentNum(usr.getCommentNum());
				uvo.setFansNum(usr.getFansNum());
				uvo.setAttentionNum(usr.getAttentionNum());
				uvo.setBirthday(DateUtil.format(usr.getBirthday()));
				uvo.setSex(usr.getAgent());
				CustomerAttentionInfo att = new CustomerAttentionInfo();
				att.setAttentionId(vo.getUserId());
				att.setBeConcernedId(vo.getBeViewedId());
				CustomerAttentionInfo atten = this.customerAttentionService
						.queryByAidAndBeid(att);
				if (atten != null) {
					uvo.setAttentioned(true);
				}
				List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
						.queryListByCid(vo.getBeViewedId());
				uvo.setMarkInfoList(markInfos);
				return uvo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取个人用户信息时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<UserVo> matchMobiles(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			String[] mobileList = vo.getMobiles().split(";");
			List<UserInfo> users = null;
			if (mobileList != null && mobileList.length > 0) {
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("mobileList", mobileList);
				users = this.userService.getUserListByMobiles(paraMap);
			}
			List<UserVo> userList = new ArrayList<UserVo>();
			if (users != null && !users.isEmpty()) {
				for (UserInfo user : users) {
					UserVo uv = new UserVo();
					uv.setUserId(user.getUserId());
					if (StringUtils.isNotBlank(user.getUserName())) {
						uv.setNickName(user.getUserName());
					} else {
						uv.setNickName(user.getUserId());
					}
					if (StringUtils.isNoneBlank(user.getHeaderPath())) {
						uv.setPortrait(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ user.getHeaderPath());
					}
					uv.setMobile(user.getMobile());
					CustomerAttentionInfo att = new CustomerAttentionInfo();
					att.setAttentionId(vo.getUserId());
					att.setBeConcernedId(user.getUserId());
					CustomerAttentionInfo atten = this.customerAttentionService
							.queryByAidAndBeid(att);
					if (atten != null) {
						uv.setAttentioned(true);
					}
					List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
							.queryListByCid(user.getUserId());
					uv.setMarkInfoList(markInfos);
					userList.add(uv);
				}
			}
			return userList;
		} else {
			log.info("requestId:" + head.getRequestId() + ",匹配用户手机号码时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<UserVo> search(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			String userId = vo.getUserId();
			// 过滤掉已关注的用户
			CustomerAttentionInfo att = new CustomerAttentionInfo();
			att.setAttentionId(userId);
			List<String> userIds = this.customerAttentionService
					.queryByAidOrBeid(att);
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("pageStart", pageStart);
			paraMap.put("pageEnd", pageEnd);
			if (userIds != null && !userIds.isEmpty()) {
				paraMap.put("userIds", userIds);
			}
			paraMap.put("search", vo.getSearch());
			List<UserVo> list = new ArrayList<UserVo>();
			List<UserInfo> userList = this.userService.queryPage(paraMap);
			if (userList != null && !userList.isEmpty()) {
				for (UserInfo usr : userList) {
					UserVo uvo = new UserVo();
					uvo.setUserId(usr.getUserId());
					if (StringUtils.isBlank(usr.getUserName())) {
						uvo.setNickName(usr.getUserId());
					} else {
						uvo.setNickName(usr.getUserName());
					}
					if (StringUtils.isNoneBlank(usr.getHeaderPath())) {
						uvo.setPortrait(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ usr.getHeaderPath());
					}
					uvo.setPersonalSign(usr.getPersonalSign());
					uvo.setCommentNum(usr.getCommentNum());
					uvo.setFansNum(usr.getFansNum());
					uvo.setAttentionNum(usr.getAttentionNum());
					uvo.setBirthday(DateUtil.format(usr.getBirthday()));
					uvo.setSex(usr.getAgent());
					CustomerAttentionInfo attention = new CustomerAttentionInfo();
					attention.setAttentionId(vo.getUserId());
					attention.setBeConcernedId(usr.getUserId());
					CustomerAttentionInfo atten = this.customerAttentionService
							.queryByAidAndBeid(attention);
					if (atten != null) {
						uvo.setAttentioned(true);
					}
					List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
							.queryListByCid(usr.getUserId());
					uvo.setMarkInfoList(markInfos);
					list.add(uvo);
				}
			}
			return list;
		} else {
			log.info("requestId:" + head.getRequestId() + ",搜索用户列表时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<UserVo> getFansOfOnhundredUser(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			List<UserVo> list = new ArrayList<UserVo>();
			List<UserInfo> userList = this.userService.queryFansOfOnehundred();
			List<UserInfo> userList2 = null;
			if (userList != null && !userList.isEmpty()) {
				int size = userList.size();
				Integer pageStartRandom = 0;
				if (size > 30) {
					userList2 = new ArrayList<UserInfo>();
					while (true) {
						pageStartRandom = new Random().nextInt(size);
						userList2.add(userList.get(pageStartRandom));
						if (userList2.size() > 29) {
							break;
						} else {
							continue;
						}
					}
					userList = userList2;
				}
			}
			if (userList != null && !userList.isEmpty()) {
				for (UserInfo usr : userList) {
					UserVo uvo = new UserVo();
					uvo.setUserId(usr.getUserId());
					if (StringUtils.isBlank(usr.getUserName())) {
						uvo.setUserName(usr.getUserId());
					} else {
						uvo.setUserName(usr.getUserName());
					}
					if (StringUtils.isNoneBlank(usr.getHeaderPath())) {
						uvo.setHeaderPath(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ usr.getHeaderPath());
					}
					uvo.setPersonalSign(usr.getPersonalSign());
					uvo.setFansNum(usr.getFansNum());
					uvo.setBirthday(DateUtil.format(usr.getBirthday()));
					uvo.setSex(usr.getAgent());
					List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
							.queryListByCid(usr.getUserId());
					uvo.setMarkInfoList(markInfos);
					list.add(uvo);
				}
			}
			return list;
		} else {
			log.info("requestId:" + head.getRequestId() + ",推荐关注人列表时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}

	}

}
